package leetcode.Hot100;

/**
 * @author Cheng Jun
 * Description: 提交LeetCode 报错 测试案例几万个，有可能是内存溢出，也有可能是真的错了，但我感觉代码没错。还是参考Trie2 的实现好点。
 * @version 1.0
 * @date 2021/12/13 20:59
 * 腾讯二面
 */
public class Trie1 {

    private TrieNode<Character> trieNode = new TrieNode(null, 26);

    public Trie1() {
    }

    public static void main(String[] args) {
        Trie1 trie1 = new Trie1();
        trie1.insert("apple");
        trie1.insert("app");
        System.out.println(trie1.search("app"));
    }

    public void insert(String word) {
        TrieNode<Character> cur = this.trieNode;
        for (int i = 0; i < word.length(); i++) {
            if (cur.children[word.charAt(i) - 'a'] == null) {
                cur.children[word.charAt(i) - 'a'] = new TrieNode<>(word.charAt(i), 26);
            }
            cur = cur.children[word.charAt(i) - 'a'];
        }
        // 最后一个字符是单词的结束，所以设置其 isWord 为 true
        cur.isWord = true;
    }

    public boolean search(String word) {
        TrieNode<Character> cur = this.trieNode;
        for (int i = 0; i < word.length(); i++) {
            if (cur.children[word.charAt(i) - 'a'] != null && cur.children[word.charAt(i) - 'a'].value == word.charAt(i)) {
                cur = cur.children[word.charAt(i) - 'a'];
            } else {
                return false;
            }
        }
        return cur.isWord;
    }

    public boolean startsWith(String prefix) {
        TrieNode<Character> cur = this.trieNode;
        for (int i = 0; i < prefix.length(); i++) {
            if (cur.children[prefix.charAt(i) - 'a'] != null && cur.children[prefix.charAt(i) - 'a'].value == prefix.charAt(i)) {
                cur = cur.children[prefix.charAt(i) - 'a'];
            } else {
                return false;
            }
        }
        return true;
    }

    class TrieNode<T> {
        // 是否为单词
        private boolean isWord = false;
        private T value;
        private TrieNode<T>[] children;

        public TrieNode(T value, int length) {
            this.value = value;
            this.children = new TrieNode[26];
        }
    }
}
